
import relationalStore from '@ohos.data.relationalStore'
import common from '@ohos.app.ability.common'
import Logger from './Logger'
import { ColumnInfo, ColumnType } from '../bean/ColumnInfo'
import preferences from '@ohos.data.preferences'
const DB_FILENAME : string = 'HeTaoHealthy.db'

class DbUtils{
  rdbStore: relationalStore.RdbStore

  initDB(context:common.UIAbilityContext): Promise<void>{
    let config : relationalStore.StoreConfig = {
      name : DB_FILENAME,
      securityLevel:relationalStore.SecurityLevel.S1
    }
    return new Promise<void>((resolve,reject) => {
      relationalStore.getRdbStore(context,config)
        .then(rdbStore =>{
          this.rdbStore = rdbStore
          Logger.debug('rdbStore 初始化完成')
          resolve()
        })
        .catch(reason =>{
          Logger.debug('rdbStore 初始化异常',JSON.stringify(reason))
          reject(reason)
        })
    })

  }

  //创建
  createTable(createSQL:string) : Promise<void>{
    return new Promise<void>((resolve,reject) => {
      this.rdbStore.executeSql(createSQL)
        .then(() =>{
          Logger.debug('创建表成功' ,createSQL)
          resolve()
        })
        .catch(err =>{
          Logger.debug('创建表失败,' ,err.message,JSON.stringify(err))
          reject(err)
        })
    })
  }

  //插入
  insertTable(tableName :string,object : any,columns:ColumnInfo[]){
    return new Promise((resolve,reject) =>{
      //object 是对象，需要转换成具体的参数值格式
      let value = this.buildValueBucket(object,columns)
      this.rdbStore.insert(tableName,value,(err,id ) =>{
        if (err) {
          Logger.error('新增失败 新增id:'+JSON.stringify(err))
          reject(err)
        }else {
          Logger.debug('新增成功 新增id:'+id.toString())
          resolve(id)
        }
      })
    })
  }

  //更新
  updateTable(tableName :string,object : any,columns:ColumnInfo[]){
    return new Promise((resolve,reject) =>{
      //object 是对象，需要转换成具体的参数值格式
      let value = this.buildValueBucket(object,columns)
      let predicates = new relationalStore.RdbPredicates("DB_FILENAME");
      //predicates.equalTo("NAME", "Lisa");
      this.rdbStore.update(value,predicates,(err,rows ) =>{
        if (err) {
          Logger.error('更新失败 更新rows:'+JSON.stringify(err))
          reject(err)
        }else {
          Logger.debug('新增成功 更新rows:'+rows.toString())
          resolve(rows)
        }
      })
    })
  }

  //删除
  deleteTable(preferences : relationalStore.RdbPredicates){
    return new Promise((resolve,reject) =>{
      //object 是对象，需要转换成具体的参数值格式
      this.rdbStore.delete(preferences,(err,rows ) =>{
        if (err) {
          Logger.error('删除失败'+JSON.stringify(err))
          reject(err)
        }else {
          Logger.debug('删除成功 删除行数'+rows.toString())
          resolve(rows)
        }
      })
    })
  }

  //查询
  quertForList<T>(preferences : relationalStore.RdbPredicates,columns:ColumnInfo[]): Promise<T[]>{
    return new Promise((resolve,reject) =>{
      //object 是对象，需要转换成具体的参数值格式
      this.rdbStore.query(preferences,columns.map(info => info.columnName),(err,result ) =>{
        if (err) {
          Logger.error('查询失败'+JSON.stringify(err))
          reject(err)
        }else {
          Logger.debug('查询成功 查询行数'+result.rowCount.toString())
          resolve(this.parseResultSet(result,columns))
        }
      })
    })
  }

  parseResultSet<T> (result : relationalStore.ResultSet,columns:ColumnInfo[] ) : T[]{
    //1.声明返回结果
    let arr = []
    if(result.rowCount <= 0){
      return arr
    }


    while (!result.isAtLastRow){
      result.goToNextRow()
      let obj = {}
      columns.forEach((info)=>{
        let val = null;
        switch (info.type){
          case ColumnType.LONG:
          val = result.getLong(result.getColumnIndex(info.columnName))
          break;
          case ColumnType.DOUBLE:
            val = result.getDouble(result.getColumnIndex(info.columnName))
            break;
          case ColumnType.STRING:
            val = result.getString(result.getColumnIndex(info.columnName))
            break;
          case ColumnType.BLOB:
            val = result.getBlob(result.getColumnIndex(info.columnName))
            break;
        }
        obj[info.name] = val
      })
      arr.push(obj)
    }
    return arr
  }

  buildValueBucket(object : any,columns:ColumnInfo[]) : relationalStore.ValuesBucket{
    let value = {}
    columns.forEach(info =>{
      let val = object[info.name]
      if(typeof val !== 'undefined'){
        value[info.columnName] = object[info.name]
      }

    })
    return value
  }
}

let dbUtils = new DbUtils()
export default dbUtils as DbUtils